import { HttpException, HttpStatus, Inject, Injectable } from '@nestjs/common';
import { PrismaService } from 'src/prisma/prisma.service';
import { Prisma } from '@prisma/client';
import { SavePageMDto } from './dto/save-page.dto';

@Injectable()
export class PageService {
  @Inject(PrismaService) private prismaService: PrismaService;

  async get_page(path: string) {
    const data = await this.prismaService.page.findUnique({
      where: {
        path,
      },
    });

    return { data };
  }

  async get_page_list(
    page: number,
    size: number,
    filter: string,
    filterFields: string,
    dev: boolean = false,
  ) {
    const filterFieldsArr = filterFields
      ? filterFields.split(',').map((ele) => {
          return {
            [ele]: { contains: filter },
          };
        })
      : [];
    const where = filter ? { OR: filterFieldsArr } : {};
    const total = await this.prismaService.page.count({
      where,
    });
    const data = await this.prismaService.page.findMany({
      where,
      skip: (page - 1) * size,
      take: size,
    });
    let fields: Prisma.PageFieldRefs;
    if (dev) {
      fields = this.prismaService.page.fields;
    }
    return {
      data,
      pager: {
        page,
        per_page: size,
        total,
      },
      ...(dev && {
        fields: Object.values(fields).map((field) => ({
          value: field.name,
          label: field.name,
        })),
      }),
    };
  }
  async save_page(savePage: SavePageMDto) {
    const { id, ...rest } = savePage;
    if (id) {
      const data = await this.prismaService.page.update({
        where: {
          id,
        },
        data: {
          ...savePage,
        },
      });
      return {
        data,
        message: '保存成功',
        messageType: 'success',
      };
    } else {
      const foundPage = await this.prismaService.page.findUnique({
        where: {
          path: savePage.path,
        },
      });
      if (!foundPage) {
        await this.prismaService.page.create({
          data: rest,
        });
        return {
          message: '创建成功',
          messageType: 'success',
        };
      } else {
        throw new HttpException('路径已存在', HttpStatus.BAD_REQUEST);
      }
    }
  }

  async delete_page(id: number) {
    try {
      await this.prismaService.page.delete({ where: { id } });
    } catch (error) {
      if (
        error instanceof Prisma.PrismaClientKnownRequestError &&
        error.code === 'P2025'
      ) {
        throw new HttpException('页面不存在', HttpStatus.BAD_REQUEST);
      }
      throw error;
    }

    return {
      message: '删除成功',
      messageType: 'success',
    };
  }
  async delete_batch_page(id: number[]) {
    const deleteResult = await this.prismaService.page.deleteMany({
      where: {
        id: {
          in: id,
        },
      },
    });

    if (deleteResult.count === 0) {
      throw new HttpException('页面不存在', HttpStatus.BAD_REQUEST);
    }

    return {
      message: '删除成功',
      messageType: 'success',
    };
  }
  async has_page(path: string) {
    const foundPath = await this.prismaService.page.findUnique({
      where: { path },
    });
    if (foundPath) {
      throw new HttpException('路径已存在', HttpStatus.BAD_REQUEST);
    } else {
      return '可用的路径';
    }
  }
}
